package com.neusoft.elmboot.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.neusoft.elmboot.mapper.UserMapper;
import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.service.UserService;
import com.neusoft.elmboot.util.CommonUtil;

@Service
public class UserServiceImpl implements UserService{

	@Autowired
	private UserMapper userMapper;
	
	@Override
	public User getUserByIdByPass(User user) {
		//取出盐值
		String salt = userMapper.getSaltById(user.getUserId());
		//md5加密
		String hashedPwd = DigestUtils.md5DigestAsHex((user.getPassword() + salt).getBytes());
		hashedPwd = DigestUtils.md5DigestAsHex((hashedPwd).getBytes());
		hashedPwd = DigestUtils.md5DigestAsHex((hashedPwd + salt).getBytes());
		user.setPassword(hashedPwd + salt);
		return userMapper.getUserByIdByPass(user);
	}
	
	@Override
	public int getUserById(String userId) {
		return userMapper.getUserById(userId);
	}
	
	@Override
	public int saveUser(User user) {
		String salt = CommonUtil.getUUID_8();
		String hashedPwd = DigestUtils.md5DigestAsHex((user.getPassword() + salt).getBytes());
		hashedPwd = DigestUtils.md5DigestAsHex((hashedPwd).getBytes());
		hashedPwd = DigestUtils.md5DigestAsHex((hashedPwd + salt).getBytes());
		user.setPassword(hashedPwd + salt);
		return userMapper.saveUser(user);
	}
	
	@Override
	public int updateUserImgById(User user) {
		return userMapper.updateUserImgById(user);
	}
	
	@Override
	public int updateUserById(User user) {
		return userMapper.updateUserById(user);
	}

	@Override
	public int updatePasswordById(User user,String newPass) {
		if(getUserByIdByPass(user)!=null) {
			String salt = CommonUtil.getUUID_8();
			String hashedPwd = DigestUtils.md5DigestAsHex((newPass + salt).getBytes());
			hashedPwd = DigestUtils.md5DigestAsHex((hashedPwd).getBytes());
			hashedPwd = DigestUtils.md5DigestAsHex((hashedPwd + salt).getBytes());
			user.setPassword(hashedPwd + salt);
			return userMapper.updatePasswordById(user);
		}
		else return 2;
	}
	
	@Override
	public int IsBusiness(String userId) {
		return userMapper.IsBusiness(userId);
	}
}
